import { Content } from '@/models/content.model';
import { Customization } from '@/models/customization.model';
import { Entry } from '@/models/entry.model';
import { Resume } from '@/models/resume.model';
import { User } from '@/models/user.model';
import { responseMessage } from '@/utils';
import { Inject, Injectable } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { InjectConnection, InjectModel } from '@nestjs/sequelize';
import { QueryTypes } from 'sequelize';
import { Sequelize } from 'sequelize-typescript';
@Injectable()
export class SyncService {
  constructor(
    @InjectConnection('resume')
    private sequelize: Sequelize,
    @InjectModel(User)
    private readonly userModel: typeof User,
    @InjectModel(Resume)
    private readonly resumeModel: typeof Resume,
    @InjectModel(Content)
    private readonly contentModel: typeof Content,
    @InjectModel(Entry)
    private readonly entryModel: typeof Entry,
    @InjectModel(Customization)
    private readonly customization: typeof Customization,

    @Inject(REQUEST)
    private readonly request: Request & { user: { userId: number } },
  ) {}

  async syncUser(params) {
    try {
      const { from, to } = params;

      const users: any[] = await this.sequelize.query(
        `select * from user_info where id>=${from} and id < ${to} `,
        {
          type: QueryTypes.SELECT,
        },
      );
      for (let i = 0; i < users.length; i++) {
        await this.userModel.create({
          id: users[i].id,
          openId: users[i].openid,
          account: users[i].account,
          nickName: users[i].nickName,
          avatar: users[i].avatarUrl,
          type: users[i].type,
          password: users[i].password,
          created_time: users[i].create_time,
        });
        await this.syncResume(users[i].id);
      }
      return users?.length;
    } catch (e) {
      return responseMessage(e, '同步失败!', -1);
    }
  }
  async searchResume({ name, phone }) {
    const resumes: any[] = await this.sequelize.query(
      `select * from resume_list where deleted=0 and name='${name}' and phone_number='${phone}'`,
      {
        type: QueryTypes.SELECT,
      },
    );
    return resumes;
  }
  async syncResume(userid) {
    const resumes: any[] = await this.sequelize.query(
      `select * from resume_list where userid=${userid} and deleted=0 and name!='百捷' and email!='123456@qq.com'`,
      {
        type: QueryTypes.SELECT,
      },
    );
    for (let i = 0; i < resumes.length; i++) {
      let birthDay = null;
      if (resumes[i].birth_day) {
        const s = resumes[i].birth_day.indexOf('-') != -1 ? '-' : '.';
        const [year, month] = resumes[i].birth_day.split(s);
        birthDay = { year: +year, month: +month };
      }
      const detailsOrder = ['name', 'email', 'phoneNumber'];
      if (resumes[i].gender != null) {
        detailsOrder.push('gender');
      }
      if (resumes[i].working_years != null) {
        detailsOrder.push('workingYears');
      }
      if (birthDay != null) {
        detailsOrder.push('birthDay');
      }
      if (resumes[i].politicsStatus != null) {
        detailsOrder.push('politicsStatus');
      }
      // if (resumes[i].arrival_time_name != null) {
      //   detailsOrder.push('arrivalTime');
      // }
      if (resumes[i].maritalStatus != null) {
        detailsOrder.push('maritalStatus');
      }
      if (resumes[i].nationality != null) {
        detailsOrder.push('nationality');
      }
      if (resumes[i].nativePlace != null) {
        detailsOrder.push('nativePlace');
      }
      if (resumes[i].height != null) {
        detailsOrder.push('height');
      }
      if (resumes[i].weight != null) {
        detailsOrder.push('weight');
      }
      const resume = await this.resumeModel.create({
        // id: resumes[i].id,
        userId: resumes[i].userid,
        templateId: null,
        oldresumeId: resumes[i].id,
        name: resumes[i].name,
        birthDay: birthDay,
        showAge: 1,
        photoObj: {
          photo: resumes[i].photo,
          showPhoto: resumes[i].showPhoto,
        },
        gender: resumes[i].gender,
        email: resumes[i].email,
        phoneNumber: resumes[i].phone_number,
        resumeThumbnail: resumes[i].resume_thumbnail,
        expJob: resumes[i].position,
        expCity: resumes[i].city,
        expectedSalary: resumes[i].remuneration_name,
        arrivalTime: resumes[i].arrival_time_name,
        nativePlace: resumes[i].nativePlace,
        nationality: resumes[i].nationality,
        address: null,
        maritalStatus: resumes[i].maritalStatus,
        politicsStatus: resumes[i].politicsStatus,
        workingYears: resumes[i].working_years,
        height: resumes[i].height,
        weight: resumes[i].weight,
        detailsOrder: detailsOrder,
        language: resumes[i].language,
        deleted: resumes[i].deleted,
      });

      await this.syncResumeContent(
        resumes[i].id,
        resume.id,
        resumes[i].userid,
        resumes[i].module_order ? JSON.parse(resumes[i].module_order) : [],
      );
    }
  }
  async syncResumeContent(oldResumeId, resumeid, userid, module_order) {
    const resumeContents: any[] = await this.sequelize.query(
      `select * from resume_content where pid=${oldResumeId} `,
      {
        type: QueryTypes.SELECT,
      },
    );
    const items = {
      educationInfo: {
        displayName: '教育经历',
        iconKey: 'cap',
        sectionType: 'education',
      },
      workExperienceInfo: {
        displayName: '工作经历',
        iconKey: 'briefcase',
        sectionType: 'work',
      },
      projectExperienceInfo: {
        displayName: '项目经历',
        iconKey: 'folderOpen',
        sectionType: 'project',
      },
      schoolExperienceInfo: {
        displayName: '校园经历',
        iconKey: 'landmark',
        sectionType: 'school',
      },
      relatedSkills: {
        displayName: '技能特长',
        iconKey: 'guitar',
        sectionType: 'skills',
      },
      credential: {
        displayName: '荣誉证书',
        iconKey: 'award',
        sectionType: 'certificate',
      },
      custom: {
        displayName: '自定义',
        iconKey: 'lightbulb',
        sectionType: 'custom',
      },
      internshipInfo: {
        displayName: '实习经历',
        iconKey: 'penClip',
        sectionType: 'internship',
      },
      selfevaluation: {
        displayName: '自我评价',
        iconKey: 'chartUser',
        sectionType: 'selfevaluation',
      },
      hobby: {
        displayName: '兴趣爱好',
        iconKey: 'guitar',
        sectionType: 'hobby',
      },
    };
    // const sectionOrder = {
    //   one: { leftSectionChildren: [] },
    //   two: { leftSectionChildren: [], rightSectionChildren: [] },
    // };
    // const defaultSectionOrder = {
    //   one: {
    //     leftSectionChildren: [
    //       'education',
    //       'work',
    //       'project',
    //       'school',
    //       'internship',
    //       'certificate',
    //       'skills',
    //       'selfevaluation',
    //       'hobby',
    //       'custom',
    //     ],
    //   },
    //   two: {
    //     leftSectionChildren: ['skills'],
    //     rightSectionChildren: [
    //       'education',
    //       'work',
    //       'project',
    //       'school',
    //       'internship',
    //       'certificate',
    //       'selfevaluation',
    //       'hobby',
    //       'custom',
    //     ],
    //   },
    // };

    // module_order = module_order.sort((a, b) => a.order - b.order);
    if (module_order.length) {
      // const list = module_order
      //   .map((o) => items[o.key]?.sectionType)
      //   .filter(Boolean);
      // sectionOrder.one.leftSectionChildren = list;
      // list.forEach((t) => {
      //   if (defaultSectionOrder.two) {
      //     if (defaultSectionOrder.two.leftSectionChildren.includes(t)) {
      //       sectionOrder.two.leftSectionChildren.push(t);
      //     }
      //     if (defaultSectionOrder.two.rightSectionChildren.includes(t)) {
      //       sectionOrder.two.rightSectionChildren.push(t);
      //     }
      //   }
      // });
    }
    if (resumeContents && resumeContents.length) {
      const content = JSON.parse(resumeContents[0]?.content || '{}');
      for (const i in content) {
        if (items[i]) {
          const item = content[i];
          let contentResult;
          if (item.length) {
            if (i == 'custom') {
              contentResult = await this.contentModel.create({
                ...items[i],
                displayName: item[0]?.selfTitle,
                resumeId: resumeid,
                userId: this.request.user.userId,
              });
            } else {
              contentResult = await this.contentModel.create({
                ...items[i],
                resumeId: resumeid,
                userId: this.request.user.userId,
              });
            }

            // if (!module_order.length) {
            //   sectionOrder.one.leftSectionChildren.push(items[i].sectionType);
            //   if (defaultSectionOrder.two) {
            //     if (
            //       defaultSectionOrder.two.leftSectionChildren.includes(
            //         items[i].sectionType,
            //       )
            //     ) {
            //       sectionOrder.two.leftSectionChildren.push(
            //         items[i].sectionType,
            //       );
            //     }
            //     if (
            //       defaultSectionOrder.two.rightSectionChildren.includes(
            //         items[i].sectionType,
            //       )
            //     ) {
            //       sectionOrder.two.rightSectionChildren.push(
            //         items[i].sectionType,
            //       );
            //     }
            //   }
            //   // if (
            //   //   sectionOrder.two.leftSectionChildren.length >
            //   //   sectionOrder.two.rightSectionChildren.length
            //   // ) {
            //   //   sectionOrder.two.rightSectionChildren.push(
            //   //     items[i].sectionType,
            //   //   );
            //   // } else {
            //   //   sectionOrder.two.leftSectionChildren.push(items[i].sectionType);
            //   // }
            // }
            for (let j = 0; j < item.length; j++) {
              const entruItem = item[j];
              if (!entruItem) {
                console.log(entruItem);
                console.log('oldResumeId', oldResumeId);
                console.log('item', JSON.stringify(item));
              } else {
                let startDate = null;
                if (entruItem.startTime) {
                  const s = entruItem.startTime.indexOf('-') != -1 ? '-' : '.';
                  const [year, month] = entruItem.startTime.split(s);
                  startDate = { year: +year, month: +month };
                }
                let endDate = null;
                if (entruItem.endTime) {
                  const s = entruItem.endTime.indexOf('-') != -1 ? '-' : '.';
                  const [year, month] = entruItem.endTime.split(s);
                  endDate = { year: +year, month: +month };
                }
                await this.entryModel.create({
                  description:
                    entruItem.detail ||
                    entruItem.jobContent ||
                    entruItem.course,
                  title: entruItem.school || entruItem.name,
                  subTitle: entruItem.profession || entruItem.position,
                  educationBackground: entruItem.educationBackground || null,
                  contentId: contentResult.id,
                  order: j,
                  userId: this.request.user.userId,
                  list: entruItem.specilSkill,
                  isHidden: module_order.length
                    ? !module_order.find((t) => t.key == i)?.isShow
                    : false,
                  startDate: startDate,
                  endDate: endDate,
                });
              }
            }
          } else {
            // const index = sectionOrder.one.leftSectionChildren.findIndex(
            //   (s) => {
            //     return s == items[i]?.sectionType;
            //   },
            // );
            // if (index != -1) {
            //   sectionOrder.one.leftSectionChildren.splice(index, 1);
            // }
            // const index2 = sectionOrder.two.leftSectionChildren.findIndex(
            //   (s) => {
            //     return s == items[i]?.sectionType;
            //   },
            // );
            // if (index2 != -1) {
            //   sectionOrder.two.leftSectionChildren.splice(index2, 1);
            // }
            // const index3 = sectionOrder.two.rightSectionChildren.findIndex(
            //   (s) => {
            //     return s == items[i]?.sectionType;
            //   },
            // );
            // if (index3 != -1) {
            //   sectionOrder.two.rightSectionChildren.splice(index3, 1);
            // }
          }
        }
      }
    }
    await this.customization.create({
      layout: {
        selected: 'one',
        colsFromDetails: {
          top: 'one',
          left: 'two',
          right: 'two',
        },
        detailsPosition: 'left',
        colWidthsFromDetails: {
          top: {
            leftWidth: 50,
            rightWidth: 50,
          },
          left: {
            leftWidth: 37,
            rightWidth: 63,
          },
          right: {
            leftWidth: 60,
            rightWidth: 40,
          },
        },
      },
      header: {
        position: 'top',
        showLabel: true,
        detailsArrangement: 'column',
        detailsDisplayLeftRight: 'icon',
        photoObj: { size: 'L', shape: 'portrait', showPhoto: true },
      },
      // sectionOrder: sectionOrder,
      spacing: {
        header: {
          position: 'top',
          showLabel: true,
          detailsArrangement: 'column',
          detailsDisplayLeftRight: 'icon',
        },
        module: {
          marginVertical: 1,
          marginHorizontal: 3,
        },
        fontSize: 3,
        lineHeight: 4,
        spacingFactor: 5,
        marginVertical: 4,
        marginHorizontal: 2,
      },
      title: {
        style: 'boxleft',
        showIcon: true,
        titleBkg: {
          a: 0.12,
          b: 191,
          g: 117,
          r: 21,
        },
      },
      colors: {
        light: {
          textColor: {
            a: 1,
            b: 67,
            g: 67,
            r: 67,
          },
          accentColor: {
            a: 1,
            b: 191,
            g: 117,
            r: 21,
          },
          backgroundColor: {
            a: 0.16,
            b: 191,
            g: 117,
            r: 21,
          },
        },
        strong: {
          textColor: {
            a: 1,
            b: 38,
            g: 38,
            r: 38,
          },
          accentColor: {
            a: 1,
            b: 191,
            g: 117,
            r: 21,
          },
          backgroundColor: {
            a: 1,
            b: 255,
            g: 255,
            r: 255,
          },
        },
      },
      template: 'tpl1',
      templateId: 5,
      resumeId: resumeid,
      userId: this.request.user.userId,
      applyAccentColor: ['headings', 'progressBars'],
      sectionOrder: {
        one: {
          leftSectionChildren: [
            'education',
            'work',
            'project',
            'school',
            'internship',
            'certificate',
            'skills',
            'selfevaluation',
            'hobby',
            'custom',
          ],
        },
        two: {
          leftSectionChildren: ['skills'],
          rightSectionChildren: [
            'education',
            'work',
            'project',
            'school',
            'internship',
            'certificate',
            'selfevaluation',
            'hobby',
            'custom',
          ],
        },
      },
    });
  }
  async syncOrders(userid) {
    const orders = await this.sequelize.query(
      `select * from order_list where user_id=${userid} `,
      {
        type: QueryTypes.SELECT,
      },
    );
    for (let i = 0; i < orders.length; i++) {}
  }
  async syncVip(userid) {
    const vips = await this.sequelize.query(
      `select * from vip_level where userid=${userid} `,
      {
        type: QueryTypes.SELECT,
      },
    );
    for (let i = 0; i < vips.length; i++) {}
  }

  async syncResumeById({ id }) {
    const res = await this.resumeModel.findOne({
      where: {
        oldresumeId: id,
        userId: this.request.user.userId,
      },
    });
    if (res) {
      return responseMessage(null, '简历已存在', -1);
    }
    const resumes: any[] = await this.sequelize.query(
      `select * from resume_list where id=${id}`,
      {
        type: QueryTypes.SELECT,
      },
    );
    const resumeDetail: any = resumes[0];
    let birthDay = null;
    let weightHeight = null;
    if (resumeDetail.birth_day) {
      const s = resumeDetail.birth_day.indexOf('-') != -1 ? '-' : '.';
      const [year, month] = resumeDetail.birth_day.split(s);
      birthDay = { year: +year, month: +month };
    }
    const detailsOrder = ['name', 'email', 'phoneNumber'];
    if (resumeDetail.gender != null) {
      detailsOrder.push('gender');
    }
    if (resumeDetail.working_years != null) {
      detailsOrder.push('workingYears');
    }
    if (birthDay != null) {
      detailsOrder.push('birthDay');
    }
    if (resumeDetail.politicsStatus != null) {
      detailsOrder.push('politicsStatus');
    }
    // if (resumes[i].arrival_time_name != null) {
    //   detailsOrder.push('arrivalTime');
    // }
    if (resumeDetail.maritalStatus != null) {
      detailsOrder.push('maritalStatus');
    }
    if (resumeDetail.nationality != null) {
      detailsOrder.push('nationality');
    }
    if (resumeDetail.nativePlace != null) {
      detailsOrder.push('nativePlace');
    }
    if (resumeDetail.height != null || resumeDetail.weight != null) {
      detailsOrder.push('weightHeight');
      weightHeight = {};
      if (resumeDetail.height != null) {
        weightHeight.height = resumeDetail.height;
      }
      if (resumeDetail.weight != null) {
        weightHeight.weight = resumeDetail.weight;
      }
    }
    const resume = await this.resumeModel.create({
      // id: resumes[i].id,
      userId: this.request.user.userId,
      templateId: null,
      oldresumeId: resumeDetail.id,
      name: resumeDetail.name,
      birthDay: birthDay,
      showAge: 1,
      photoObj: {
        photo: resumeDetail.photo,
        showPhoto: resumeDetail.showPhoto,
      },
      gender: resumeDetail.gender,
      email: resumeDetail.email,
      phoneNumber: resumeDetail.phone_number,
      resumeThumbnail: resumeDetail.resume_thumbnail,
      expJob: resumeDetail.position,
      expCity: resumeDetail.city,
      expectedSalary: resumeDetail.remuneration_name,
      arrivalTime: resumeDetail.arrival_time_name,
      nativePlace: resumeDetail.nativePlace,
      nationality: resumeDetail.nationality,
      address: null,
      maritalStatus: resumeDetail.maritalStatus,
      politicsStatus: resumeDetail.politicsStatus,
      workingYears: resumeDetail.working_years,
      weightHeight: weightHeight,
      detailsOrder: detailsOrder,
      language: resumeDetail.language,
      deleted: resumeDetail.deleted,
    });

    await this.syncResumeContent(
      resumeDetail.id,
      resume.id,
      resumeDetail.userid,
      resumeDetail.module_order ? JSON.parse(resumeDetail.module_order) : [],
    );
    return resume.id;
  }
}
